package com.sise.bl.controller;

import com.sise.bl.entity.Cart;
import com.sise.bl.entity.User;
import com.sise.bl.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/cart")
@SessionAttributes({"msg","loginUser"})
public class CartController {
    @Autowired
    @Qualifier("cartService")
    private CartService cartService;

    @RequestMapping(value = "/create")
    public ModelAndView create(@RequestParam("pid") String pid, ModelAndView modelAndView, Model model) {

        //1.判断是否已经登录
        User user = (User) model.getAttribute("loginUser");

        if (user == null) {
            modelAndView.addObject("msg", "添加购物车必须先登录！");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        //2.商品的id和用户id
        int uid = user.getUid();

        cartService.createCart(uid, pid);

        modelAndView.setViewName("cartSuccess");
        return modelAndView;
    }

    @RequestMapping(value = "/show")
    public ModelAndView show(ModelAndView modelAndView,Model model) {
        System.out.println("==============");
        //1.判断是否已经登录
        User user = (User) model.getAttribute("loginUser");
        if (user == null) {
            modelAndView.addObject("msg", "添加购物车必须先登录！");
            modelAndView.setViewName("login");

            return modelAndView;
        }

        //2.获取参数
        int uid = user.getUid();

        //3.调用业务逻辑进行数据查询
        List<Cart> list = cartService.findAll(uid);

        modelAndView.addObject("list", list);
        modelAndView.setViewName("cart");
        return modelAndView;
    }

    @RequestMapping(value = "/delete")
    public String delete(@RequestParam("cid") String cid) {
        //调用业务逻辑进行删除
        cartService.deleteCartByCid(cid);
        //转发到展示的处理方法中
        return "redirect:/cart/show";
    }

    @RequestMapping(value = "/update")
    public String update(@RequestParam("cid") String cid, @RequestParam("price") String price, @RequestParam("cnum") String cnum) {
        //调用业务逻辑进行删除
        cartService.updateCartByCid(cid, price, cnum);
        //转发到展示的处理方法中
        return "redirect:/cart/show";
    }

    @RequestMapping(value = "/clear")
    public String clear(@RequestParam("uid") String uid) {
        //调用业务逻辑进行删除
        cartService.clearCart(uid);
        //转发到展示的处理方法中
        return "redirect:/cart/show";
    }
}
